# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

configData

svmTop <- configData["svmTop", "value"] %>%
  as.numeric()
rfTop <- configData["rfTop", "value"] %>%
  as.numeric()

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

diffData <- read_csv("../../potential/Markers.csv")

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
  .$Metabolite

data <- read.csv(opt$i, header = T) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  column_to_rownames("SampleID") %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame()

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

borutaRs <- Boruta(x, y, maxRuns = 1000)
decData <- borutaRs$finalDecision %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  set_colnames(c("Metabolite", "decision"))
print(decData)

statData <- attStats(borutaRs) %>%
  rownames_to_column("Metabolite")
outData <- statData %>%
  arrange(desc(medianImp)) %>%
  column_to_rownames("Metabolite")
outFileName <- paste0(parent, "/Decision_Info.csv")
write.csv(outData, outFileName)


sortData <- borutaRs$ImpHistory %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  rowwise() %>%
  do({
       result <- as.data.frame(.)
       data <- result[-1] %>%
         unlist() %>%
         discard(~is.infinite(.x))
       median <- median(data, na.rm = T)
       result$median <- median
       result
     }) %>%
  arrange(median) %>%
  as.data.frame()

print(head(outData))

sortNames <- sortData$Metabolite

decLelvels <- c("Shadow", "Rejected", "Tentative", "Confirmed")
fillColors <- setNames(c("#0000FF", "#FF0000", "#FFFF00", "#00FF00"), decLelvels)

head(borutaRs$ImpHistory)

imp <- borutaRs$ImpHistory %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  gather("Sample", "Value", -Metabolite) %>%
  left_join(decData, by = c("Metabolite")) %>%
  mutate_at(vars("decision"), function(x) {
    ifelse(is.na(x), "Shadow", as.character(x))
  }) %>%
  mutate(Metabolite = factor(Metabolite, levels = sortNames)) %>%
  mutate(decision = factor(decision, levels = decLelvels)) %>%
  as.data.frame()

p <- ggplot(imp, mapping = aes(x = Metabolite, y = Value, fill = decision)) +
  ylab("Importance") +
  xlab("") +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1, vjust = 1), legend.position = 'top',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11),
        axis.text.y = element_text(size = 8.8), axis.title.y = element_text(size = 11),
        axis.title.x = element_text(size = 12), panel.border = element_rect(size = 0.75)
  ) +
  geom_boxplot() +
  scale_fill_manual("finalDecision", values = fillColors)

pdfFileName <- paste0(parent, "/Decision_Boxplot.pdf")


rowNum <- nrow(outData) + 3
width <- max(2 + (rowNum - 10) * 0.25, 2) + 2
print(width)

ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = 6)









